package com.xilihui.xlh.core.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;

import com.xilihui.xlh.core.app.BaseApplication;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * SharedPreferences统一管理类
 */
public class SPUtil {

    /**
     * SharedPreferences文件名
     */
    private static final String FILE_NAME = "qianruiji";

    // key值
    public static final String TOKEN = "token";
    public static final String DEVICE_TOKEN = "device_token";
    public static final String USER_ID = "user_id";
    public static final String EXPIRE_TIME = "expire_time";
    public static final String isLoadImageIn4G = "wifi";
    public static final String PUSH = "push";
    public static final String UMENG_DEVICE_TOKEN = "umeng_device_token";
    public static final String APK_UPDATE_TIME = "apk_update_time";
    public static final String PRELOAD_UPDATE_TIME = "preload_update_time";
    public static final String MOBILE = "mobile";
    public static final String KEYWORD = "keyword";
    public static final String VERSION = "version";
    public static final String AREA = "area";
    public static final String HOME = "home";
    public static final String AUTH = "auth";
    public static final String SPEC = "spec";
    public static final String UPGRADE = "upgrade";
    public static final String IS_LOGIN_ACTIVITY_OPEN = "login";
    public static final String SIFT = "sift";
    public static final String ALL_GROUP_SIFT = "all_group_sift";
    public static final String GUIDE = "guide";
    public static final String CHARACTER = "character";
    public static final String SHOP_NAME = "shop_name";
    public static final String LOGO = "logo";
    public static final String RONG_TOKEN = "rong_token";
    public static final String SEALTALK_LOGIN_ID = "rong_loginid";
    public static final String FRIEND_ID = "friend_id";
    public static final String SEALTALK_LOGIN_LOGO = "rong_logo";
    public static final String SEALTALK_LOGIN_NAME = "rong_name";
    public static final String USERNAME = "username";
    public static final String ADDRESS = "address";
    public static final String ALERT_PERMISSION_REMIND = "alert_permission_remind";
    public static final String SOURCING = "sourcing";
    
    public static final String NICK = "nick";
    public static final String IS_LOGIN = "is_login";
    public static final String LAT = "lat";
    public static final String LNG = "lng";
    public static final String HEAD_IMAGE = "head_image";
    public static final String SIGN = "sign";
    
    public static final String TIANZHUANG = "tianzhuang";
    public static final String WA_ID = "wa_id";
    public static final String ARGENT_ID = "agent_id";
    public static final String PAY_TYPE = "pay_type";
    
    public static final String STORE_TZ = "is_store_tiaozhuang";
    
    public static final String PHONE = "phone";

    /**
     * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
     *
     * @param context
     * @param key
     * @param object
     */
    public static void put(Context context, String key, Object object) {
        SharedPreferences sp;
        if (context == null) {
            sp = BaseApplication.get().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        } else {
            sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        }
        SharedPreferences.Editor editor = sp.edit();
        if (object == null) {
            return;
        }
        if (object instanceof String) {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        } else {
            editor.putString(key, object.toString());
        }
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 得到保存数据的方法，我们根据默认值得到保存的数据的具体类型，然后调用相对于的方法获取值
     *
     * @param context
     * @param key
     * @param defaultObject
     * @return
     */
    public static Object get(Context context, String key, Object defaultObject) {
        SharedPreferences sp;
        if (context == null) {
            sp = BaseApplication.get().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        } else {
            sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        }
        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        }
        return null;
    }

    /**
     * 移除某个key值已经对应的值
     *
     * @param context
     * @param key
     */

    public static void remove(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 清除所有数据
     *
     * @param context
     */
    public static void clear(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 查询某个key是否已经存在
     *
     * @param context
     * @param key
     * @return
     */
    public static boolean contains(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.contains(key);
    }

    /**
     * 返回所有的键值对
     *
     * @param context
     * @return
     */
    public static Map<String, ?> getAll(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.getAll();
    }

    /**
     * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
     *
     * @author zhy
     */
    private static class SharedPreferencesCompat {
        private static final Method sApplyMethod = findApplyMethod();

        /**
         * 反射查找apply的方法
         *
         * @return
         */
        @SuppressWarnings({"unchecked", "rawtypes"})
        private static Method findApplyMethod() {
            try {
                Class clz = SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e) {
            }
            return null;
        }

        /**
         * 如果找到则使用apply执行，否则使用commit
         *
         * @param editor
         */
        public static void apply(SharedPreferences.Editor editor) {
            try {
                if (sApplyMethod != null) {
                    sApplyMethod.invoke(editor);
                    return;
                }
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
            editor.commit();
        }
    }

    /**
     * 写入对象
     *
     * @param key
     * @param object 注意序列化
     * @throws Exception
     */
    public static void putObject(String key, Object object) {

        SharedPreferences sharedPreferences = BaseApplication.get().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            String temp = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
            editor.putString(key, temp);
            editor.apply();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取对象
     *
     * @param key
     * @return
     */
    public static Object getObject(String key) {
        SharedPreferences sharedPreferences = BaseApplication.get().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        String temp = sharedPreferences.getString(key, "");
        ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(temp.getBytes(), Base64.DEFAULT));
        Object o = null;
        try {
            ObjectInputStream ois = new ObjectInputStream(bais);
            o = ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return o;
    }
}